﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;

namespace Guog.Common.Controls.DropDownControl
{
    internal sealed class DropDownContainer : Form, IMessageFilter
    {
        private bool m_freeze;
        public bool Freeze
        {
            get { return m_freeze; }
            set { m_freeze = value; }
        }

        public delegate void DropWindowArgs(DropState state);
        public event DropWindowArgs DropStateChange;

        public DropDownContainer(Control dropDownItem)
        {
            this.FormBorderStyle = FormBorderStyle.None;
            dropDownItem.Location = new Point(1, 1);
            this.Controls.Add(dropDownItem);
            this.StartPosition = FormStartPosition.Manual;
            this.ShowInTaskbar = false;
            Application.AddMessageFilter(this);
        }

        //public bool PreFilterMessage(ref Message m)
        //{
        //    if (!Freeze && this.Visible && (Form.ActiveForm == null || !Form.ActiveForm.Equals(this)))
        //    {
        //        OnDropStateChange(eDropState.Closing);
        //        this.Close();
        //    }


        //    return false;
        //}

        
        protected void OnDropStateChange(DropState state)
        {
            if (DropStateChange != null)
                DropStateChange(state);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            e.Graphics.DrawRectangle(Pens.Gray, new Rectangle(0, 0, this.ClientSize.Width - 1, this.ClientSize.Height - 1));
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            Application.RemoveMessageFilter(this);
            this.Controls.RemoveAt(0); //prevent the control from being disposed
            base.OnClosing(e);
        }

        #region IMessageFilter 成员

        public bool PreFilterMessage(ref Message m)
        {
            if (!Freeze && this.Visible && (Form.ActiveForm == null || !Form.ActiveForm.Equals(this)))
            {
                OnDropStateChange(DropState.Closing);
                this.Close();
            }


            return false;
        }

        #endregion
    }
}
